<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div class="">
      <div class="p-2 text-right">
        <a-button type="primary" @click="handleAdd" size="small">新增</a-button>
      </div>
      <Table :dataSource="list" :columns="columns" :pagination="false" :customRow="customRow">
        <template #move>
          &#9769
        </template>
        <template #field="{ record, index }">
          <Select
            :options="mainColumnOptions"
            v-model:value="record['mainColumn']"
            class="w-full"
            @change="(e) => getMainColumn(e, record, 'mainColumn', index)"
          />
        </template>
        <template #tztj="{ record, index }">
          <div class="flex">
            <Select
              :options="firstBracketOptions"
              v-model:value="record['firstBracket']"
              class="w-80px"
              style="margin-right: 5px"
            />

            <Select
              :options="fieldNameOptions"
              v-model:value="record['fieldName']"
              class="w-200px"
              style="margin-right: 5px"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_FIELD"
              @change="(val) => getFieldName(val, record)"
              show-search
              optionFilterProp="label"
            />
            <Select
              :options="compareOptions2"
              v-model:value="record['compare']"
              class="w-80px"
              style="margin-right: 5px"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_DEPT"
            />
            <Select
              :options="compareOptions3"
              v-model:value="record['compare']"
              class="w-80px"
              style="margin-right: 5px"
              v-else-if="record['isText']"
            />

            <Select
              :options="compareOptions"
              v-model:value="record['compare']"
              class="w-80px"
              style="margin-right: 5px"
              v-else
            />
            <div
              class="w-150px"
              style="margin-right: 5px"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_FIELD"
            >
              <!-- <Input v-model:value="record['columnName']" /> -->
              <FormCtl
                v-if="record['fieldName']"
                :formCode="record['formCode']"
                :fieldName="record['fieldName']"
                v-model:value="record['columnName']"
              />
            </div>
            <div
              class="w-150px"
              style="margin-right: 5px"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_DEPT_LEVEL"
            >
              <Input v-model:value="record['columnName']" />
            </div>
            <Select
              :options="roleOptions"
              v-model:value="record['role']"
              class="w-200px"
              style="margin-right: 5px"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_ROLE"
            />
            <TreeSelect
              :field-names="{ label: 'name', value: 'code' }"
              v-model:value="record['userDept']"
              class="w-200px"
              style="margin-right: 5px"
              show-search
              allow-clear
              tree-default-expand-all
              :tree-data="userDeptOptions"
              tree-node-filter-prop="name"
              v-if="record['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_DEPT"
            />
            <Select
              :options="firstBracketOptions"
              v-model:value="record['twoBracket']"
              class="w-80px"
              style="margin-right: 5px"
            />
            <Select
              :options="logicalOptions"
              v-model:value="record['logical']"
              class="w-80px"
              style="margin-right: 5px"
              v-if="index != list.length - 1"
            />
          </div>
        </template>
        <template #action="{ index }">
          <div class="flex">
            <a-button type="primary" class="mr-2" size="small" @click="handleAdd">新增</a-button>
            <a-button type="primary" size="small" @click="handleDelete(index)">删除</a-button>
          </div>
        </template>
      </Table>
      <div class="pl-4 mt-2">
        <div>注：</div>
        <div>1、复选框如果被勾选则值为1，未被勾选则值为0</div>
        <div>2、=>表示属于某个部门，包括该部门本身，及其下级所有部门 </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted, reactive, nextTick } from 'vue';
  import { Form, Input, Table, Select, TreeSelect } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import { isArray } from '/@/utils/is';
  import { getDepartment } from '/@/api/system/system';
  import { getRoleMultilSel } from '/@/api/system/system';

  import { FormCtl } from '/@/components/FormCtl';

  import {
    mainColumnOptions,
    firstBracketOptions,
    columns,
    setMsgProp,
    compareOptions,
    logicalOptions,
    compareOptions2,
    compareOptions3,
  } from './configrationCombinationModal.data';
  import { FormField, WorkflowPredefineDb } from '/@/enums/flowManage';

  export default defineComponent({
    name: 'ConfigrationCombinationModal',
    components: {
      BasicModal,
      Table,
      Select,
      Input,
      TreeSelect,
      FormCtl,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const useFlow = useFlowStore();
      const flowEdit = computed(() => useFlow.flowEdit);
      const dataRef = ref<Recordable>({});
      const linkProps = ref('');
      const formData = ref<Recordable>({});
      const list = ref<any>([]);
      const from = ref('');
      const to = ref('');
      const getTitle = '配置';

      const fieldNameOptions: any = ref([]);
      const roleOptions: any = ref([]);
      const userDeptOptions: any = ref([]);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '65%' });
        try {
          list.value = [];
          await nextTick();
          console.log('data?.list', data?.list);
          list.value = data?.list ? [...data.list] : [];
          linkProps.value = useFlow?.flowEdit.linkProps;
          from.value = '';
          to.value = '';
          if (isArray(list.value) && list.value.length > 0) {
            from.value = list.value[0].from;
            to.value = list.value[0].to;
          }
          fieldNameOptions.value = [];
          if (isArray(data?.fields)) {
            data.fields.forEach((item) => {
              fieldNameOptions.value.push({
                fieldType: item.fieldType,
                macroType: item.macroType,
                formCode: item.formCode,
                type: item.type,
                typeDesc: item.typeDesc,
                value: item.name,
                label: item.title,
              });
            });
            if (isArray(list.value)) {
              list.value.forEach((item) => {
                if (item['mainColumn'] == WorkflowPredefineDb.COMB_COND_TYPE_FIELD) {
                  const obj = fieldNameOptions.value.find((el) => el.value == item.fieldName);
                  item['formCode'] = obj?.formCode;
                }
              });
            }
          }
          getDepartmentData();
          getRoleMultilSelData();
          console.log({
            list: list.value,
            linkProps: linkProps.value,
            from: from.value,
            to: to.value,
            fieldNameOptions,
            fields: data?.fields,
          });
        } catch (err) {
          console.log(err);
        }
      });

      const getDepartmentData = async () => {
        try {
          userDeptOptions.value = (await getDepartment()) || [];
        } catch (err) {
          console.log(err);
        }
      };
      const getRoleMultilSelData = async () => {
        await getRoleMultilSel().then((res) => {
          let data = res || [];
          data.forEach((item) => {
            item.value = item.code;
            item.label = item.description;
          });
          roleOptions.value = data;
        });
      };

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          formData.value = Object.assign({}, dataRef.value);
          list.value.forEach((item) => {
            for (let v in item) {
              if (item[v] == null || item[v] == 'null') {
                item[v] == '';
              }
            }
          });
          const hiddenCondition = await setMsgProp(list.value, {
            configFrom: unref(from),
            configTo: unref(to),
          });
          console.log('hiddenCondition', hiddenCondition);
          closeModal();
          emit('success', hiddenCondition, unref(list));
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const getMainColumn = (val, record, col, index) => {
        record[col] = val;
        console.log({ val, record, index });
        let columnValue = val;
        record['fieldType'] = '';
        record['fieldNameType'] = '';

        if (columnValue == WorkflowPredefineDb.COMB_COND_TYPE_FIELD) {
          record.columnName = '';
          record.compare = '=';
        }

        changeFieldName(index);
      };

      function changeFieldName(str) {
        let record = list.value[str];
        console.log("record",record)
        let obj = record;
        let mainColumn = record.mainColumn;
        let index = obj.selectedIndex;
        let fieldType = obj.options?obj.options[index]?.getAttribute('id'):'';
        let fieldNameType = obj.options?obj.options[index]?.getAttribute('name'):'';

        let isText = false; // 是否为字符型
        if (fieldType == FormField.FIELD_TYPE_TEXT || fieldType == FormField.FIELD_TYPE_VARCHAR) {
          // 如果不是公式宏控件
          if (fieldNameType != 'macro_formula_ctl') {
            isText = true;
          }
        }
        record['isText'] = isText;
        list.value[str] = { ...record };
      }

      const handleAdd = () => {
        const obj = isArray(fieldNameOptions.value) ? fieldNameOptions.value[0] : {};
        list.value.push({
          from: from.value,
          to: to.value,
          mainColumn: 'comb_field',
          fieldName: obj?.value,
          fieldType: obj?.fieldType,
          formCode: obj?.formCode,
          columnName: '',
          compare: '=',
          firstBracket: '',
          value: '',
          twoBracket: '',
          logical: '',
          role: '',
          userDept: '',
        });
        list.value = [...list.value];
        console.log('list.value', list.value);
      };
      const handleDelete = (index) => {
        list.value.splice(index, 1);
        list.value = [...list.value];
      };

      //选择表单
      const getFieldName = (val, record) => {
        if (val) {
          const obj = fieldNameOptions.value.find((item) => item.value == val);
          record['fieldType'] = obj?.fieldType;
          record['formCode'] = obj?.formCode;

          let index = obj.selectedIndex;
          let fieldNameType = obj.options?obj.options[index]?.getAttribute('name'):'';
          let isText = false; // 是否为字符型
          if (obj?.fieldType == FormField.FIELD_TYPE_TEXT || obj?.fieldType == FormField.FIELD_TYPE_VARCHAR) {
            // 如果不是公式宏控件
            if (fieldNameType != 'macro_formula_ctl') {
              isText = true;
            }
          }
          record['isText'] = isText;
        } else {
          record['fieldType'] = '';
          record['formCode'] = '';
        }
      };

      let source = 0; // 源目标数据序号
      let target = 0; // 目标数据序号
      // Table行拖拽
      function customRow(record, index) {
        // 只有当具有管理权限时才启用
        // if (!listPage.value.canUserManage) {
        //   return;
        // }
        return {
          props: {
            // draggable: 'true'
          },
          style: {
            // cursor: 'pointer',
          },
          // 鼠标移入
          onMouseenter: (event) => {
            // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
          },
          onMousedown: (event) => {
            if (event.srcElement.tagName === 'TD') {
              let cellIndex = event.srcElement.cellIndex;
              // 如果点击的是第1列（第0列为复选框列），则使可以拖动
              // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
              if (cellIndex == 0) {
                event.target.draggable = true; // 使可以拖动
              }
            }
          },
          // 开始拖拽
          onDragstart: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到源目标数据序号
            source = index;
            console.log(record, index, 'source');
          },
          // 拖动元素经过的元素
          onDragover: (event) => {
            // 兼容 IE
            let ev = event || window.event;
            // 阻止默认行为
            ev.preventDefault();
          },
          // 鼠标松开
          onDrop: (event) => {
            // 兼容IE
            let ev = event || window.event;
            // 阻止冒泡
            ev.stopPropagation();
            // 得到目标数据序号
            target = index;
            const dataFrom = list.value[source];
            list.value.splice(source, 1);
            list.value.splice(target, 0, dataFrom);
            console.log('list', list.value);
            event.target.parentElement.draggable = false; // 取消拖动
            // console.log(record, index, 'target', source, target);
          },
          onDblclick: () => {},
        };
      }
      return {
        registerModal,
        getTitle,
        handleSubmit,
        list,
        columns,
        mainColumnOptions,
        firstBracketOptions,
        fieldNameOptions,
        compareOptions,
        roleOptions,
        userDeptOptions,
        logicalOptions,
        getMainColumn,
        compareOptions2,
        WorkflowPredefineDb,
        handleAdd,
        handleDelete,
        compareOptions3,
        getFieldName,
        customRow,
      };
    },
  });
</script>
